/**
 * Filename: PublishActivity.java
 *
 * @author Firefly
 * @contact postfirefly@163.com
 * @time 2016/3/19 18:51
 */
package com.github.postsanf.yinian.activity;

import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.github.postsanf.yinian.BaseActivity;
import com.github.postsanf.yinian.BaseApplication;
import com.github.postsanf.yinian.R;
import com.github.postsanf.yinian.adapter.PublishWallAdapter;
import com.github.postsanf.yinian.constants.ACTIONs;
import com.github.postsanf.yinian.constants.CommonConstants;
import com.github.postsanf.yinian.constants.SelectedImg;
import com.github.postsanf.yinian.constants.YNSingleton;
import com.github.postsanf.yinian.service.ModifyTypeService;
import com.github.postsanf.yinian.service.UpLoadService;
import com.github.postsanf.yinian.utils.Bimp;
import com.github.postsanf.yinian.utils.SizeFormat;
import com.github.postsanf.yinian.utils.SpUtils;
import com.github.postsanf.yinian.utils.StringUtils;
import com.github.postsanf.yinian.utils.WrapContentGridLayoutManager;
import com.github.postsanf.yinian.view.SpacesItemDecoration;
import com.umeng.analytics.MobclickAgent;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

public class PublishWithLocationActivity extends BaseActivity implements View.OnClickListener, AdapterView.OnItemClickListener {
    private Toolbar mToolbar;
    private EditText et_write_status;
    private ArrayList<String> imgUris = new ArrayList<String>();
    private List<String> tempUris = new ArrayList<String>();
    private String gimid;
    private int groupId;
    private String statusContent;
    private PublishWallAdapter mAdapter;
    private ProgressDialog mProgressDialog;             // 进度条
    private LinearLayout ll_publish_top;
    private RadioGroup rgPush;
    private int isPush = 0;
    private LinearLayout ll_is_push;
    private RecyclerView rv_publish_image_list;
    private int aIsOfficial = 0;// 默认不是官方相册
    SharedPreferences.Editor editor;
    private long upstorge;
    private String fsize;
    private ConnectivityManager mConnectivityManager;
    private NetworkInfo netInfo;
    private TextView publish_location_content;
    private TextView bigpic_select_tv;
    public static boolean IsSmall = false;
    private String eplace = "";
    private String edit;
    private ProgressDialog pd;
    private File mTempDir;
    Handler mHandler = new Handler() {
        public void handleMessage(android.os.Message msg) {
            if (msg.what == 1) {
                if (pd != null)
                    pd.dismiss();
                if (netInfo != null && netInfo.isAvailable()) {
                    if (netInfo.getType() == ConnectivityManager.TYPE_WIFI) {
                        //WiFi网络
                        if (edit != null && edit.equals("edit")) {
                            moidfyUpload(false);
                        } else {
                            doUpImg(false);
                        }
                    } else if (netInfo.getType() == ConnectivityManager.TYPE_MOBILE) {
                        //3g网络
                        int netfrist = getSharedPreferences(ACTIONs.mynetwork, 0).getInt(ACTIONs.networkFrist, 0);
                        String nettype = getSharedPreferences(ACTIONs.mynetwork, 0).getString(ACTIONs.networkType, "");
                        if (!nettype.equals("") && nettype.equals(ACTIONs.network3GWIFI)) {
                            if (edit != null && edit.equals("edit")) {
                                moidfyUpload(false);
                            } else {
                                doUpImg(false);
                            }
                        } else {
                            if (netfrist == 0) {
                                FristNetWork(fsize);
                                editor.putInt(ACTIONs.networkFrist, 1);
                                editor.commit();
                            } else {
                                SecondNetWork(fsize);
                            }
                        }
                    }
                } else {
                    if (pd != null)
                        pd.dismiss();
                }
                //doUpImg();
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.yn_activity_publishwithlocation);
        registerBroadcastReceiver();
        InitData();
        initView();
    }

    private void InitData() {
        IsSmall = false;
        edit = getIntent().getStringExtra("edit");
        if (edit != null && edit.equals("edit")) {
            SelectedImg.mSelectedImage.clear();
            SelectedImg.mSelectedImage.addAll(YNSingleton.getInstance().getCurStatus().getUrl());
        }
        tempUris = YNSingleton.getInstance().getCurStatus().getThumbnail();
        groupId = YNSingleton.getInstance().getCurAlbum().getGroupid();
        gimid = YNSingleton.getInstance().getCurAlbum().getGimid();
        editor = getSharedPreferences(ACTIONs.mynetwork, 0).edit();
        mConnectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        netInfo = mConnectivityManager.getActiveNetworkInfo();
        mTempDir = new File(Environment.getExternalStorageDirectory(), "yinian/temp");
        if (!(mTempDir.mkdir() || mTempDir.isDirectory())) {
            mTempDir.mkdirs();
        }
    }

    private void initView() {
        aIsOfficial = StringUtils.isOfficialGroup(YNSingleton.getInstance().getCurAlbum().getGtype()) ? 1 : 0;
        mToolbar = (Toolbar) findViewById(R.id.publish_toolbar);
        setSupportActionBar(mToolbar);
        mToolbar.setNavigationIcon(R.drawable.ic_return);
        rgPush = (RadioGroup) findViewById(R.id.push_radioGroup);
        ll_publish_top = (LinearLayout) findViewById(R.id.ll_publish_top);
        ll_is_push = (LinearLayout) findViewById(R.id.ll_is_push);
        et_write_status = (EditText) findViewById(R.id.et_write_status);
        if (edit != null && edit.equals("edit")) {
            String etext = YNSingleton.getInstance().getCurStatus().getEtext();
            if (etext != null) {
                et_write_status.setText(etext);
            }
        }
        rv_publish_image_list = (RecyclerView) findViewById(R.id.rv_publish_image_list);
        rv_publish_image_list.setLayoutManager(new WrapContentGridLayoutManager(this, 4));
        mAdapter = new PublishWallAdapter(this, imgUris);
        View mAddImg = View.inflate(this, R.layout.yn_include_add_photo, null);
        mAddImg.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                publishAdd();
            }
        });
        mAdapter.setFooterView(mAddImg);
        rv_publish_image_list.setAdapter(mAdapter);
        rv_publish_image_list.setHasFixedSize(true);
        SpacesItemDecoration decoration = new SpacesItemDecoration(1);
        rv_publish_image_list.addItemDecoration(decoration);
        rv_publish_image_list.setItemViewCacheSize(30);
        if (tempUris.size() > 0) {
            imgUris.addAll(tempUris);
            updateImgs();
        }
        String tab = getString(R.string.numberofme);
        if (tab.equals(String.valueOf(application.getCurID())) && StringUtils.isOfficialGroup(YNSingleton.getInstance().getCurAlbum().getGtype())) {
            ll_is_push.setVisibility(View.VISIBLE);
        }
        rgPush.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                switch (checkedId) {
                    case R.id.push_rb_no:
                        isPush = 0;
                        break;
                    case R.id.push_rb_yes:
                        isPush = 1;
                        break;
                }
            }
        });
        publish_location_content = (TextView) findViewById(R.id.publish_location_content);
        if (edit != null && edit.equals("edit")) {
            String place = YNSingleton.getInstance().getCurStatus().getEplace();
            if (place != null) {
                publish_location_content.setText(place);
                eplace = place;
            }
        }
        findViewById(R.id.location).setOnClickListener(this);
        bigpic_select_tv = (TextView) findViewById(R.id.bigpic_select_tv);
        bigpic_select_tv.setOnClickListener(this);

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.ll_publish_top:
                ll_publish_top.setFocusable(true);
                break;
            case R.id.location:
                startActivity(new Intent(PublishWithLocationActivity.this, PublishLocationMapActivity.class).putExtra("ll", publish_location_content.getText().toString()));
                break;
            case R.id.bigpic_select_tv:
                startActivity(new Intent(PublishWithLocationActivity.this, PicBigSmallSelectActivity.class).putExtra("upstorge", upstorge));
                break;
        }
    }


    // 发布动态
    private void sendStatus() {
        application.setUpToken("");
        statusContent = et_write_status.getText().toString().trim();
        if (imgUris.size() <= 0) {
            showToast("选择图片上传");
            return;
        }
        if (!IsSmall) {
            pd = ProgressDialog.show(PublishWithLocationActivity.this, "", "发布中...", false,
                    false);
            mHandler.sendEmptyMessage(1);
        } else {
            pd = ProgressDialog.show(PublishWithLocationActivity.this, "", "压缩中...", false,
                    false);
            new Thread() {
                @Override
                public void run() {
                    super.run();
                    for (int i = 0; i < SelectedImg.mSelectedImage.size(); i++) {
                        String mubiaostr = Bimp.compressImage2(SelectedImg.mSelectedImage.get(i), mTempDir);
                        SelectedImg.mSelectedImage.set(i, mubiaostr);
                    }
                    mHandler.sendEmptyMessage(1);
                }
            }.start();
        }
    }

    public void SecondNetWork(String fsize) {
        final AlertDialog dlg = new AlertDialog.Builder(this).create();
        dlg.show();
        Window window = dlg.getWindow();
        window.setContentView(R.layout.publish_network_dialog);
        TextView tt = (TextView) window.findViewById(R.id.pp_title);
        tt.setText(">_< 您关闭了使用流量上传开关，你在使用3g/4g网络环境下，这会消耗您" + fsize + "流量，确定继续上传吗？");
        final TextView ok = (TextView) window.findViewById(R.id.btn_ep_ok);
        ok.setText("取消");
        ok.setBackgroundColor(getResources().getColor(R.color.white));
        ok.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                dlg.cancel();
            }
        });
        final TextView cancel = (TextView) window
                .findViewById(R.id.btn_ep_cancel);
        cancel.setText("仅一次");
        cancel.setBackgroundColor(getResources().getColor(R.color.white));
        cancel.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                if (edit != null && edit.equals("edit")) {
                    moidfyUpload(false);
                } else {
                    doUpImg(false);
                }
                dlg.cancel();
            }
        });
    }

    public void FristNetWork(String fsize) {
        final AlertDialog dlg = new AlertDialog.Builder(this).create();
        dlg.show();
        Window window = dlg.getWindow();
        window.setContentView(R.layout.publish_network_dialog);
        TextView tt = (TextView) window.findViewById(R.id.pp_title);
        tt.setText("您现在处于移动网络环境下，将消耗" + fsize + "流量，是否使用流量继续上传?");
        final TextView ok = (TextView) window.findViewById(R.id.btn_ep_ok);
        ok.setText("不允许");
        ok.setBackgroundColor(getResources().getColor(R.color.white));
        ok.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                if (edit != null && edit.equals("edit")) {
                    moidfyUpload(true);
                } else {
                    doUpImg(true);
                }
                dlg.cancel();
            }
        });
        final TextView cancel = (TextView) window
                .findViewById(R.id.btn_ep_cancel);
        cancel.setText("确定");
        cancel.setBackgroundColor(getResources().getColor(R.color.white));
        cancel.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                editor.putString(ACTIONs.networkType, ACTIONs.network3GWIFI);
                editor.commit();
                if (edit != null && edit.equals("edit")) {
                    moidfyUpload(false);
                } else {
                    doUpImg(false);
                }
                dlg.cancel();
            }
        });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_publish, menu);
        MenuItem action_publish = menu.findItem(R.id.action_publish);
        if (aIsOfficial == 1) {
            action_publish.setTitle("投稿");
        } else {
            action_publish.setTitle("上传");
        }
        return true;
    }

    @Override
    public void onBackPressed() {
        new AlertDialog.Builder(PublishWithLocationActivity.this).setMessage("确定不要上传照片了吗？")
                .setPositiveButton(R.string.yn_app_ok, new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) {
                        Intent mIntent = new Intent(ACTIONs.actionCloseAlbum);
                        mIntent.putExtra(ACTIONs.aIsClearSelect, 0);
                        sendBroadcast(mIntent);
                        SelectedImg.mSelectedImage.clear();
                    }
                }).setNegativeButton(R.string.yn_app_cancel, new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int whichButton) {
            }
        }).show();

    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                // 发消息取消上传
                new AlertDialog.Builder(PublishWithLocationActivity.this).setMessage("确定不要上传照片了吗？")
                        .setPositiveButton(R.string.yn_app_ok, new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int whichButton) {
                                Intent mIntent = new Intent(ACTIONs.actionCloseAlbum);
                                mIntent.putExtra(ACTIONs.aIsClearSelect, 0);
                                sendBroadcast(mIntent);
                                SelectedImg.mSelectedImage.clear();
                            }
                        }).setNegativeButton(R.string.yn_app_cancel, new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) {
                    }
                }).show();
                return true;
            case R.id.action_publish:
                if (aIsOfficial == 1) {
                    showToast("正在审核投稿");
                }
                sendStatus();
                String thisgtype = YNSingleton.getInstance().getCurAlbum().getGtype();
                if (thisgtype != null) {
                    if (thisgtype.equals("6") || thisgtype.equals("7") || thisgtype.equals("8")) {
                        startService(new Intent(PublishWithLocationActivity.this, ModifyTypeService.class));
                    }
                }
                break;
        }
        return super.onOptionsItemSelected(item);
    }


    private void doUpImg(boolean isPause) {
        mProgressDialog = ProgressDialog.show(this, "", CommonConstants.TIP_LOAD_UP);
        Intent mIntent = new Intent(this, UpLoadService.class);
        mIntent.setAction(ACTIONs.actionPublishPhoto);
        mIntent.putExtra(ACTIONs.aUid, application.getCurID() + "");
        mIntent.putExtra(ACTIONs.aGid, groupId + "");
        mIntent.putExtra(ACTIONs.aGimid, gimid);
        mIntent.putExtra(ACTIONs.aType, StringUtils.isOfficialGroup(YNSingleton.getInstance().getCurAlbum().getGtype()) ? 1 : 0);
        mIntent.putExtra(ACTIONs.aPush, isPush);
        mIntent.putExtra(ACTIONs.aIsOfficial, aIsOfficial);
        mIntent.putExtra(ACTIONs.aGname, YNSingleton.getInstance().getCurAlbum().getGname());
        mIntent.putExtra(ACTIONs.aContent, statusContent);
        mIntent.putExtra(ACTIONs.aEplace, eplace);
        mIntent.putExtra(ACTIONs.aisPause, isPause);
        Log.i("xjs", "IsSmall==>" + IsSmall);
        if (IsSmall) {
            mIntent.putExtra(ACTIONs.upstorage, SizeFormat.formatDouble(upstorge * 6 / 10, SizeFormat.FZ_KB));
        } else {
            mIntent.putExtra(ACTIONs.upstorage, SizeFormat.formatDouble(upstorge, SizeFormat.FZ_KB));
        }
        mIntent.putExtra(ACTIONs.upismemorycard, 0);
        mIntent.putExtra(ACTIONs.uptags, "");
        mIntent.putExtra(ACTIONs.upaudio, "");
        mIntent.putExtra(ACTIONs.upmemorytime, "");
        mIntent.putExtra(ACTIONs.upplace, "");
        mIntent.putExtra(ACTIONs.upaudiotime, "");
        mIntent.putExtra(ACTIONs.upcoverUrl, "");
        startService(mIntent);
        startActivity(new Intent(this, UpLoadActivity.class).putExtra(ACTIONs.IstoSetWifi, isPause));
        Intent upIntent = new Intent(ACTIONs.actionCloseAlbum);
        upIntent.putExtra(ACTIONs.aIsClearSelect, 1);
        sendBroadcast(upIntent);
        if (mProgressDialog != null)
            mProgressDialog.dismiss();
    }

    private void moidfyUpload(boolean isPause) {
        mProgressDialog = ProgressDialog.show(this, "", CommonConstants.TIP_LOAD_UP);
        Intent mIntent = new Intent(this, UpLoadService.class);
        mIntent.setAction(ACTIONs.modifyStatus);
        mIntent.putExtra(ACTIONs.aUid, application.getCurID() + "");
        mIntent.putExtra(ACTIONs.aEid, YNSingleton.getInstance().getCurStatus().getEid() + "");
        mIntent.putExtra(ACTIONs.aContent, et_write_status.getText().toString().trim());
        mIntent.putExtra(ACTIONs.aEplace, eplace);
        mIntent.putExtra(ACTIONs.upmemorytime, "");
        mIntent.putExtra(ACTIONs.upaudio, "");
        mIntent.putExtra(ACTIONs.upcoverUrl, "");
        mIntent.putExtra(ACTIONs.uptags, "");
        mIntent.putExtra(ACTIONs.upgname, YNSingleton.getInstance().getCurAlbum().getGname());
        mIntent.putExtra(ACTIONs.aType, StringUtils.isOfficialGroup(YNSingleton.getInstance().getCurAlbum().getGtype()) ? 1 : 0);
//        mIntent.putExtra(ACTIONs.aPush, isPush);
        if (IsSmall) {
            mIntent.putExtra(ACTIONs.upstorage, SizeFormat.formatDouble(upstorge * 6 / 10, SizeFormat.FZ_KB));
        } else {
            mIntent.putExtra(ACTIONs.upstorage, SizeFormat.formatDouble(upstorge, SizeFormat.FZ_KB));
        }
        mIntent.putExtra(ACTIONs.picType, "event");
        mIntent.putExtra(ACTIONs.aisPause, isPause);
        startService(mIntent);
        startActivity(new Intent(this, UpLoadActivity.class).putExtra(ACTIONs.IstoSetWifi, isPause));
        Intent upIntent = new Intent(ACTIONs.actionCloseAlbum);
        upIntent.putExtra(ACTIONs.aIsClearSelect, 1);
        sendBroadcast(upIntent);
        if (mProgressDialog != null)
            mProgressDialog.dismiss();
    }

    // 图片列表更新
    private void updateImgs() {
        mAdapter.notifyDataSetChanged();
    }

    public void publishAdd() {
        SpUtils.put(PublishWithLocationActivity.this, "noClear", true);
        Intent intent = new Intent(this, LocalManageActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
        intent.putExtra("isPeopleSapce", true);
        startActivity(intent);
        Intent mIntent = new Intent(ACTIONs.actionUpdateUpNum);
        sendBroadcast(mIntent);
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//		Object itemAdapter = parent.getAdapter();
//		if(itemAdapter instanceof WriteStatusGridImgsAdapter) {
//			if(position == statusImgsAdapter.getCount() - 1) {
//				ImageUtils.showImagePickDialog(this);
//			}
//		}
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        // 更新图片列表
        imgUris.clear();
        imgUris.addAll(SelectedImg.mSelectedImage);
        updateImgs();
        updateSelectTV();
    }


    // 广播接收
    private BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            switch (action) {
                case ACTIONs.actionCloseAlbum:
                    finish();
                    break;
                case ACTIONs.actionUpdateLocation:
                    if (intent != null) {
                        String location = intent.getStringExtra("location");
                        if (location.equals("不显示位置")) {
                            eplace = "";
                        } else {
                            eplace = location;
                        }
                        publish_location_content.setText(location);
                    }
                    break;
                case ACTIONs.actionUpdatePicBigSmall:
                    updateSelectTV();
                    break;

            }
        }
    };

    //注册广播
    private void registerBroadcastReceiver() {
        IntentFilter myIntentFilter = new IntentFilter();
        myIntentFilter.addAction(ACTIONs.actionCloseAlbum);
        myIntentFilter.addAction(ACTIONs.actionUpdateLocation);
        myIntentFilter.addAction(ACTIONs.actionUpdatePicBigSmall);
        this.registerReceiver(mBroadcastReceiver, myIntentFilter);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        BaseApplication.getInstance().mActivitys.remove(this);
        this.unregisterReceiver(mBroadcastReceiver);
    }


    // 友盟统计
    public void onResume() {
        super.onResume();
        MobclickAgent.onPageStart(this.getClass().getSimpleName());
        MobclickAgent.onResume(this);
        imgUris.clear();
        imgUris.addAll(SelectedImg.mSelectedImage);
        updateImgs();
        updateSelectTV();
    }

    private void updateSelectTV() {
        long totalSize = 0;
        for (int i = 0; i < SelectedImg.mSelectedImage.size(); i++) {
            String address = SelectedImg.mSelectedImage.get(i);
            if (!address.startsWith("http")) {
                File uploadImg = new File(address);
                long imgSize = uploadImg.length();
                totalSize += imgSize;
            }
        }
        upstorge = totalSize;
        fsize = SizeFormat.formatSize(totalSize);
        if (IsSmall) {
            bigpic_select_tv.setText("正常 (" + SizeFormat.formatSize(totalSize * 6 / 10) + ")");
        } else {
            bigpic_select_tv.setText("原图 (" + SizeFormat.formatSize(totalSize) + ")");
        }
    }

    public void onPause() {
        super.onPause();
        MobclickAgent.onPageEnd(this.getClass().getSimpleName());
        MobclickAgent.onPause(this);
    }
}
